package com.dl.dlcommon.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author DL
 * @create 2022-04-04 16:22
 */
@Slf4j
public class FileUtil {

    final static String WINDOWS = "windows";

    final static String LINUX = "linux";

    /**
     * linux下运行jar，通过路径获取文件的绝对路径
     * @param path  传相对路径 比如 cert/alipay/xxx.crt
     * @return  返回的路径就是放在linux服务器上的文件路径
     */
    public static String getFileAbsolutePath(String path){
        // 获取系统类型名称
        String os = System.getProperty("os.name");
        try {
            // 判断Linux环境下与Windows环境下，获取密钥文件路径
            if (os != null && os.toLowerCase().startsWith(WINDOWS)) {
                path = new ClassPathResource(path).getURL().getPath();
            } else if (os != null && os.toLowerCase().startsWith(LINUX)) {
                path = FileUtil.getFileAbsolutePathLinux(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return path;
    }

    private static String getFileAbsolutePathLinux(String path){
        // 创建临时文件，获取jar里面的配置文件
        File file = new File("/home/file/" + path);
        if(file.exists()){
            return file.getAbsolutePath();
        }
        InputStream inputStream = null;
        try {
            ClassPathResource resource = new ClassPathResource(path);
            inputStream = resource.getInputStream();
            //FileUtils.copyInputStreamToFile(inputStream, file);
            return file.getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    public static boolean upload(MultipartFile[] files, String path){
        boolean flag = true;
        for (MultipartFile file : files) {
            // 获取文件全名a.py
            String fullName = file.getOriginalFilename();
            System.out.println("fullName = " + fullName);
            // 文件上传路径
            //String templatePath = "C:\\Users\\123\\OneDrive\\桌面\\开题答辩\\个人\\public\\upload-test\\";
            String templatePath = "C:\\Users\\123\\OneDrive\\桌面\\开题答辩\\个人\\public\\upload-test\\" + path + "\\";

            // 获取文件的后缀名
            String suffix = fullName.substring(fullName.lastIndexOf("."));
            // 解决中文问题,liunx 下中文路径,图片显示问题
            String fileName = UUIDUtil.getUUID10() + suffix;

            File realPath = new File(templatePath + fileName);
            //文件上传-覆盖
            try {
                // 检测是否存在目录
                if (!realPath.exists()) {
                    realPath.mkdirs();
                }
                file.transferTo(realPath);
            } catch (Exception e) {
                flag =  false;
            }
        }
        return flag;
    }

    /**
     * 上传产品主图
     * @param files 主图
     * @param path 主图路径
     * @param productId
     * @return
     */
    public static String uploadReturnMain(MultipartFile[] files, String path, String productId){
        StringBuffer stringBuffer = new StringBuffer();
        for (MultipartFile file : files) {
            // 获取文件全名a.py
            String fullName = file.getOriginalFilename();
            // 文件上传路径
            String templatePath = "C:\\Users\\123\\OneDrive\\桌面\\开题答辩\\个人\\public\\upload-test\\" + path + "\\";
            // 获取文件的后缀名
            String suffix = fullName.substring(fullName.lastIndexOf("."));
            // 解决中文问题,liunx 下中文路径,图片显示问题
            //String fileName = UUIDUtil.getUUID10() + suffix;
            String fileName = productId + suffix;
            //System.out.println("fileName = " + fileName);

            stringBuffer.append(path).append(fileName).append(",");
            File realPath = new File(templatePath + fileName);
            //文件上传-覆盖
            try {
                // 检测是否存在目录
                if (!realPath.exists()) {
                    realPath.mkdirs();
                }
                file.transferTo(realPath);
            } catch (Exception e) {
                System.out.println("图片上传错误");
                return null;
            }
        }
        stringBuffer.setLength(stringBuffer.length() - 1);
        return String.valueOf(stringBuffer);
    }

    /**
     * 上传产品副图
     * @param files 副图
     * @param path 上传路径
     * @param productId 产品id，用来作为副图的名称
     * @return 处理后的副图名称
     */
    public static String uploadReturnSub(MultipartFile[] files, String path, String productId){
        StringBuffer stringBuffer = new StringBuffer();
        int i = 1;
        for (MultipartFile file : files) {
            // 获取文件全名a.py
            String fullName = file.getOriginalFilename();
            // 文件上传路径
            String templatePath = "C:\\Users\\123\\OneDrive\\桌面\\开题答辩\\个人\\public\\upload-test\\" + path + "\\";
            // 获取文件的后缀名
            String suffix = fullName.substring(fullName.lastIndexOf("."));
            // 解决中文问题,liunx 下中文路径,图片显示问题
            //String fileName = UUIDUtil.getUUID10() + suffix;
            String fileName = productId + "_" +  i + suffix;
            //System.out.println("fileName = " + fileName);

            stringBuffer.append(path).append(fileName).append(",");
            File realPath = new File(templatePath + fileName);
            //文件上传-覆盖
            try {
                // 检测是否存在目录
                if (!realPath.exists()) {
                    realPath.mkdirs();
                }
                file.transferTo(realPath);
                //System.out.println("realPath.getAbsolutePath() = " + realPath.getAbsolutePath());
            } catch (Exception e) {
                System.out.println("图片上传错误");
                return null;
            }
            i++;
        }
        stringBuffer.setLength(stringBuffer.length() - 1);
        return String.valueOf(stringBuffer);
    }

    /**
     * 上传规格图片
     * @return 是否成功
     */
    public static String uploadSpecsImg(MultipartFile file,String specsPrefix, String specsImgName) throws IOException {

        // 获取文件全名a.py
        String fullName = file.getOriginalFilename();
        // 文件上传路径
        String templatePath = "C:/Users/123/OneDrive/桌面/开题答辩/个人/public/upload-test" + specsPrefix;
        System.out.println("templatePath = " + templatePath);
        // 获取文件的后缀名
        String suffix = fullName.substring(fullName.lastIndexOf("."));
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //String fileName = UUIDUtil.getUUID10() + suffix;
        String fileName = specsImgName + suffix;
        System.out.println("fileName = " + fileName);

        File realPath = new File(templatePath + fileName);
        //文件上传-覆盖
        // 检测是否存在目录
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        file.transferTo(realPath);
        System.out.println("realPath.getAbsolutePath() = " + realPath.getAbsolutePath());
        return fileName;
    }



    /**
     * 上传品牌图片
     * @return 是否成功
     */
    public static String uploadBrandImg(MultipartFile file,String brandPrefix, Integer brandId) throws IOException {

        // 获取文件全名a.py
        String fullName = file.getOriginalFilename();
        // 文件上传路径
        String templatePath = "C:\\Users\\123\\OneDrive\\桌面\\开题答辩\\个人\\" + brandPrefix;
        System.out.println("templatePath = " + templatePath);
        // 获取文件的后缀名
        String suffix = Objects.requireNonNull(fullName).substring(fullName.lastIndexOf("."));
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //String fileName = UUIDUtil.getUUID10() + suffix;
        String fileName = brandId + suffix;

        File realPath = new File(templatePath + fileName);
        //文件上传-覆盖
        // 检测是否存在目录
        if (!realPath.exists()) {
            realPath.mkdirs();
        }
        file.transferTo(realPath);
        return fileName;
    }

    public static String readFile(String filePath){
        try {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            String line;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            reader.close();
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void saveToFile(String content, String filePath, String fileName) throws Exception {
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(filePath) || StringUtils.isEmpty(fileName)){
            throw new Exception("文件路径或名称不能为空");
        }
        try {
            if (!filePath.endsWith(File.separator) && !fileName.startsWith(File.separator)){
                filePath = filePath + File.separator;
            }
            if (filePath.endsWith(File.separator) && fileName.startsWith(File.separator)){
                filePath = filePath.substring(0, filePath.length() - 1);
            }

            File file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile(); // 如果文件不存在则创建新文件
            }else {
                String[] split = fileName.split("\\.");
                String fileNameSplit = split[0];
                String fileSuffixSplit = split[1];
                if (!fileNameSplit.contains("_")){
                    fileNameSplit = fileNameSplit + "_";
                }

                // 获取下一个文件名
                String nextFileName = getNextFileName(filePath, fileNameSplit, fileSuffixSplit);

                file = new File(filePath + nextFileName);
            }

            FileWriter writer = new FileWriter(file);
            // 向文件写入内容
            writer.write(content);
            writer.close(); // 关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String filePath = "D:\\DL\\Project\\my-test\\test\\src\\main\\resources\\xml";
        String fileName = "head_";
        String fileSuffix = ".xml";

        try {
            getNextFileName(filePath, fileName, fileSuffix);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getNextFileName(String filePath, String fileName, String fileSuffix) throws IOException {
        File directory = new File(filePath);
        if (!fileSuffix.startsWith(".")){
            fileSuffix = "." + fileSuffix;
        }
        String regex = fileName + "\\d{0,2}" + fileSuffix;
        File[] existingFiles = directory.listFiles((dir, name) -> name.matches(regex));

        int maxSequence = 0;

        if (existingFiles != null) {
            for (File file : existingFiles) {
                int sequence = extractSequence(file.getName());
                if (sequence > maxSequence) {
                    maxSequence = sequence;
                }
            }
        }

        int nextSequence = maxSequence + 1;
        String nextFileName;
        if (nextSequence < 10){
            // 确保序列长度为2，以便与下面的代码匹配
            nextFileName = fileName + "0" + nextSequence + fileSuffix;
        }else {
            nextFileName = fileName + nextSequence + fileSuffix;

        }
        return nextFileName;
    }

    private static int extractSequence(String fileName) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(fileName);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group());
        }
        return 0;
    }

    public static String concatPathName(String filePath, String fileName){
        if (!filePath.endsWith(File.separator) && !fileName.startsWith(File.separator)){
            filePath = filePath + File.separator;
        } else if (filePath.endsWith(File.separator) && fileName.startsWith(File.separator)){
            filePath = filePath.substring(0, filePath.length() - 1);
        }

        return filePath + fileName;
    }


}
